package com.yksj.healthtalk.ui.home;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import org.handmark.pulltorefresh.library.PullToRefreshListView;

import sfs2x.client.core.SFSEvent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yksj.healthtalk.adapter.DoctorAdapter.onClickFriendAttentionListener;
import com.yksj.healthtalk.adapter.MyDoctorDetailAdpter;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.comm.SingleBtnFragmentDialog;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonsfHttpResponseHandler;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.MessagePushService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.AppData;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.doctor.DoctorCommonServiceActivity;
import com.yksj.healthtalk.ui.doctor.DoctorInterviewNotPayActivity;
import com.yksj.healthtalk.ui.doctor.DoctorTimeNotPayActivity;
import com.yksj.healthtalk.ui.doctor.SelectPaymentOptionActivity;
import com.yksj.healthtalk.ui.doctorstation.DoctorServiceStatusContent;
import com.yksj.healthtalk.ui.friend.DoctorMainActivity;
import com.yksj.healthtalk.utils.FriendHttpUtil;
import com.yksj.healthtalk.utils.JsonParseUtils;
import com.yksj.healthtalk.utils.TimeUtil;
import com.yksj.healthtalk.utils.ToastUtil;

/**
 * 我的医生列表详细
 * @author Administrator
 *
 */
public class MyDoctorDetailListActivity extends BaseFragmentActivity implements MydoctorListener, OnClickListener, OnItemClickListener,onClickFriendAttentionListener, OnRefreshListener2<ListView> {
	private PullToRefreshListView mPullListView;
	private ListView mListView;
	private Intent intent;
	private ArrayList<CustomerInfoEntity> entities;
	private MyDoctorDetailAdpter adpter;
	private int pageSize = 1;
	private int pageNum = 20;
	private String name;
	private int id;
	private CustomerInfoEntity cacheCustomerInfoEntity;
	private AppData mAppData;
	private BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(MessagePushService.ACTION_COLLECT_FRIEND)) {
				LodingFragmentDialog.dismiss(getSupportFragmentManager());
				String result = intent.getStringExtra("result");
				if (result.equals("0")) {
					ToastUtil.showShort(context, R.string.groupNewFail);
				} else {
					FriendHttpUtil.requestAttentionTofriendsResult(context,cacheCustomerInfoEntity, mAppData);
					adpter.notifyDataSetChanged();
				}
			} else if (action.equals(SFSEvent.CONNECTION_LOST)) {
			}
		}

	};
	private String SELECTDATE;
	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.mydoctor_detail);
		mAppData = HTalkApplication.getAppData();
		initWidget();
		initData();
	}

	private void initData() {
		intent = getIntent();
		if (intent.hasExtra("name")) {
			name = intent.getStringExtra("name");
			id =Integer.valueOf(intent.getStringExtra("index"));
		}else {
			return;
		}

		titleTextV.setText(name);
		entities = new ArrayList<CustomerInfoEntity>();
		adpter = new MyDoctorDetailAdpter(entities, this, id);
		mListView.setAdapter(adpter);
		mListView.setOnItemClickListener(this);
		mPullListView.setOnRefreshListener(this);
	}
	
	@Override
	protected void onStart() {
		mPullListView.setRefreshing();
		HttpRestClient.doHttpMyDoctorDetailList(SmartFoxClient.getLoginUserId(), id + "", pageSize, pageNum,new AsyncHander());
		IntentFilter filter = new IntentFilter();
		filter.addAction(MessagePushService.ACTION_COLLECT_FRIEND);
		filter.addAction(SFSEvent.CONNECTION_LOST);
		registerReceiver(receiver, filter);
		super.onStart();
	}

	private void initWidget() {
		// TODO Auto-generated method stub
		initTitle();
		mPullListView = (PullToRefreshListView) findViewById(R.id.hall);
		mListView = mPullListView.getRefreshableView();
		mListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.list_line_layout, null));
		titleLeftBtn.setOnClickListener(this);
	}

	//
	class AsyncHander extends ObjectHttpResponseHandler {
		private LodingFragmentDialog dialog;

		@Override
		public void onFinish() {
			mPullListView.onRefreshComplete();
			super.onFinish();
		}

		@Override
		public Object onParseResponse(String content) {
			return JsonParseUtils.jsonfilter(content);
		}

		@Override
		public void onSuccess(int statusCode, Object response) {
			if (response != null) {
				if (response instanceof String) {
					ToastUtil.showShort(getApplicationContext(),response.toString());
				} else {
					if(pageSize!=1){
						for (CustomerInfoEntity entity : (ArrayList<CustomerInfoEntity>)response) {
							entities.add(entity);
						}
					}else{
					entities.clear();
					entities.addAll((ArrayList<CustomerInfoEntity>) response);
					adpter.notifyDataSetChanged();
					}
				}
			}
			super.onSuccess(statusCode, response);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (0 < position && position < entities.size() + 1) {
//			Intent intent = new Intent(getApplicationContext(), DoctorMainActivity.class);
//			intent.putExtra("id", entities.get(position - 1).getId());
//			startActivity(intent);
			FriendHttpUtil.onItemClick(this, entities.get(position - 1));
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.title_back:
			onBackPressed();
			break;
		}
	}

	@Override
	public void orderDetail(CustomerInfoEntity entity) {
		if (id == 0 || id == 1|| id == 4||id ==5||id == 6) {
			HttpRestClient.doHttpMyDoctorOrderDetail(SmartFoxClient.getLoginUserId(), entity.getOrderId(), entity.getId(), new JsonAsyncHander(id,entity));
		}else if (id == 2) {
			intent=new Intent(getApplicationContext(),DoctorServiceStatusContent.class);
			intent.putExtra("ORIDERID", entity.getOrderId());
			intent.putExtra("CUSTOMER_ID", SmartFoxClient.getLoginUserId());
			intent.putExtra("DOCTORID", entity.getId());
			intent.putExtra("tag", 1000);
			startActivity(intent);
		}
		
	}

	@Override
	public void onClickHeaderLisenter(CustomerInfoEntity info) {
		Intent intent = new Intent(getApplicationContext(), DoctorMainActivity.class);
		intent.putExtra("id", info.getId());
		startActivity(intent);
	}
	
	
	
	//退款
	/**
	 *   "name": "正在服务",
        "id": 0
        "name": "已预约服务",
        "id": 1
        "name": "已取消预约",
        "id": 2
        "name": "服务历史",
        "id": 3
        "name": "未支付服务",
        "id": 4
        "name": "支付失败服务",
        "id": 5
        "name": "可（待）退款服务",
        "id": 6
        "name": "我关注的医生",
        "id": 7
	 * @author Administrator
	 *
	 */
	class JsonAsyncHander  extends JsonsfHttpResponseHandler{
		private int id;
		private CustomerInfoEntity entity;
		public JsonAsyncHander(int id,CustomerInfoEntity entity){
			super(MyDoctorDetailListActivity.this);
			this.id =  id;
			this.entity = entity;
		}

		@Override
		public void onSuccess(int statusCode, JSONObject response) {
			if (response.containsKey("error_message")) {
					SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(),response.getString("error_message"));
			}else if(id == 0 || id == 1|| id == 5 || id == 6){//正在服务  支付失败
				if (response.containsKey("SERVICE_TYPE_ID")) {
					int service_type_id = response.getIntValue("SERVICE_TYPE_ID");
					Intent intent = new Intent();
					switch (service_type_id) {
					case 1://VIP服务
						intent.setClass(getApplicationContext(), MyDoctorCommonServiceActivity.class);
						break;
					case 2:// 预约时段 
						intent.setClass(getApplicationContext(), MyDoctorTimePayActivity.class);
						break;
					case 3://门诊预约
						intent.setClass(getApplicationContext(), MyDoctorInterviewPayActivity.class);
						break;
					}
					intent.putExtra("id", id);
					intent.putExtra("response", response.toString());
					intent.putExtra("mCustomerInfoEntity", entity);
					startActivity(intent);
				}
			}else if(id == 4){//未支付界面
				if (response.containsKey("SERVICE_TYPE_ID")) {
					int service_type_id = response.getIntValue("SERVICE_TYPE_ID");
					Intent intent = new Intent();
					switch (service_type_id) {
					case 1:// VIP服务
						intent.setClass(getApplicationContext(), DoctorCommonServiceActivity.class);
						break;
					case 2://"预约面坊
						intent.setClass(getApplicationContext(), DoctorTimeNotPayActivity.class);
						break;
					case 3://预约时段未支付界面
						intent.setClass(getApplicationContext(), DoctorInterviewNotPayActivity.class);
						break;
					}
					JSONArray array = new JSONArray();
					array.add(response);
					JSONObject jsonObject =  new JSONObject();
					jsonObject.put("witchPage", 3);
					jsonObject.put("SERVICE_ITEM_DESC", response.getString("SERVICE_ITEM_DESC"));
					jsonObject.put("TickMesg", array);
					intent.putExtra("response", jsonObject.toString());
					intent.putExtra("mCustomerInfoEntity", entity);
					startActivity(intent);
				}
			}
			super.onSuccess(statusCode, response);
		}
	}

	@Override
	public void onClickPay(final CustomerInfoEntity info) {
		try {
			SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
			SELECTDATE=format.format( new Date(Long.valueOf(info.getServiceEnd())));
		} catch (Exception e) {
			SELECTDATE=null;
		}
		
		if (!TextUtils.isEmpty(SELECTDATE)) {
			SELECTDATE = SELECTDATE.substring(0, 8);
		}else {
			SELECTDATE = null;
		}
		HttpRestClient.doHttpWalletBalanceServlet(SELECTDATE,HttpRestClient.doHttpPayment(null,SmartFoxClient.getLoginUserId(), info.getId(), info.getServiceTypeId(), info.getServiceItemId(),  info.getServiceTypeSubId(), null), new JsonsfHttpResponseHandler(this){
			@Override
			public void onSuccess(int statusCode, JSONObject object2) {
				if (object2.containsKey("error_message")) {
					SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(), object2.getString("error_message"));
					return;
				}else if (object2.containsKey("Balance")) {
					Intent intent = new Intent(getApplicationContext(),SelectPaymentOptionActivity.class);
					intent.putExtra("url", HttpRestClient.doHttpPayment(SELECTDATE,SmartFoxClient.getLoginUserId(), info.getId(), info.getServiceTypeId(), info.getServiceItemId(),  info.getServiceTypeSubId(), null));
					intent.putExtra("money",object2.getString("Balance"));
					intent.putExtra("BindPhone", object2.getString("BindPhone"));
					intent.putExtra("isSetPsw", object2.getString("isSetPsw"));
					intent.putExtra("mCustomerInfoEntity", info);
					startActivity(intent);
					finish();
				}
				super.onSuccess(statusCode, object2);
			}
		});

	}

	@Override
	public void onClickFriendAttention(int attentioned,CustomerInfoEntity entity, int positon) {
		cacheCustomerInfoEntity = FriendHttpUtil.requestAttentionTofriends(this,null, entity);
	}
	
	
	@Override
	public void onStop() {
		unregisterReceiver(receiver);
		super.onStop();
	}


	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
		pageSize = 1;
		HttpRestClient.doHttpMyDoctorDetailList(SmartFoxClient.getLoginUserId(), id + "", pageSize, pageNum,new AsyncHander());
	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
		++pageSize;
		HttpRestClient.doHttpMyDoctorDetailList(SmartFoxClient.getLoginUserId(), id + "", pageSize, pageNum,new AsyncHander());
	}
}
